package com.wujilee.mqdelaytask.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wujilee.mqdelaytask.entity.EntityDelayTask;
import com.wujilee.mqdelaytask.mapper.EntityDelayTaskGeneratedMapper;
import com.wujilee.mqdelaytask.service.Callback;
import com.wujilee.mqdelaytask.service.DelayTaskService;
import com.wujilee.mqdelaytask.service.ExecuteDelayTaskService;
import com.wujilee.mqdelaytask.service.ScheduledDelayTaskService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author liwuji
 * @date 2024/4/12
 * @desc
 **/
@Service
@EnableScheduling
public class ScheduledDelayTaskServiceImpl implements ScheduledDelayTaskService, ApplicationContextAware {
    private ApplicationContext applicationContext;
    @Resource
    private DelayTaskService delayTaskService;
    @Resource
    private ExecuteDelayTaskService executeDelayTaskService;
    @Resource
    private EntityDelayTaskGeneratedMapper delayTaskGeneratedMapper;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    @Scheduled(cron = " 0 0 30 0 0 ?")
    public void scanTask() {
        Iterable<EntityDelayTask> delayTask = delayTaskService.getDelayTask();
        Callback<EntityDelayTask> callback = (exception, task) -> {
            if (exception == null) {
                LambdaUpdateWrapper<EntityDelayTask> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.set(EntityDelayTask::getStatus, "1")
                        .eq(EntityDelayTask::getId, task.getId()).eq(EntityDelayTask::getStatus, task.getStatus());
                delayTaskGeneratedMapper.update(null, updateWrapper);
            }
            
        };
        Map<String, ExecuteDelayTaskService> beansOfType = applicationContext.getBeansOfType(ExecuteDelayTaskService.class);
        delayTask.forEach(executeDelayTaskService::execute);
    }

 
}
